﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json;

namespace db
{
    public class JsonHelper
    {
        public static string SqlDataReader2JsonForEasyUIDataGrid(int total, System.Data.SqlClient.SqlDataReader reader)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);

            
            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.Indented;
                writer.WriteStartObject();
                writer.WritePropertyName("total");
                writer.WriteValue(total);
                writer.WritePropertyName("rows");
                writer.WriteStartArray();
                while (reader.Read())
                {
                    writer.WriteStartObject();
                    for (int index = 0; index < reader.FieldCount; index++)
                    {
                        writer.WritePropertyName(reader.GetName(index));
                        writer.WriteValue(reader.GetValue(index));
                    }
                    writer.WriteEndObject();
                }
                writer.WriteEnd();
                writer.WriteEndObject();
            }

            return sb.ToString();
        }
    }
}
